package com.itheima.test;

import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.server.AppServerApplication;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@SpringBootTest(classes = AppServerApplication.class)
@RunWith(SpringRunner.class)
public class Osstest {

    /***
     * 案例：
     * 将资料1的图片上传到阿里云OSS中
     * 存放位置  /yyyy/MM/dd/文件名.jpg
     *
     * */

    @SneakyThrows
    @Test
    public void testoss() {
        //1.配置图片路径
        String path = "C:\\Users\\我还差\\Desktop\\1589335155647888.jpg";
        //2.构造FileInputStream输入流

            FileInputStream inputStream = new FileInputStream(new File(path));

        //3.拼写图片路径
        String fileName = new SimpleDateFormat("yyyy/MM/dd").format(new Date())+
                "/"+ UUID.randomUUID().toString()+path.substring(path.lastIndexOf("."));



        // 阿里云OSS相关配置
        String endpoint = "https://oss-cn-beijing.aliyuncs.com"; // 替换为您的Endpoint
        String accessKeyId = "LTAI5tF3D2C7cgrFXCtyPjDk"; // 替换为您的AccessKeyId
        String accessKeySecret = "SQoNz7tVyLHl9FdSfOBsxtBhSDLcln"; // 替换为您的AccessKeySecret
        String bucketName = "whctanhua"; // 替换为您的Bucket名称
        String objectName = fileName; // 上传到OSS的文件名

        // 创建OSSClient实例
        OSS ossClient = null;

            // 使用默认的CredentialProvider链
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 定义要上传的byte数组内容

            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);

            // 执行上传操作
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            System.out.println("上传成功，ETag: " + result.getETag());
            ossClient.shutdown();
            String url =  "https://whctanhua.oss-cn-beijing.aliyuncs.com/"+objectName;
            System.out.println(url);
        }
        @Autowired
        OssTemplate ossTemplate;
        @Test
        public void testoss2() throws FileNotFoundException {
        String path = "C:\\Users\\我还差\\Pictures\\Screenshots\\屏幕截图 2025-03-09 141024.png";
          String url =  ossTemplate.uploadFile(path, new FileInputStream(new File(path)));
          System.out.println(url);
        }

}



